package com.fh.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fh.common.api.vo.Result;
import com.fh.common.aspect.annotation.AutoLog;
import com.fh.common.constant.CommonConstant;
import com.fh.common.constant.Constant;
import com.fh.common.exception.Assert;
import com.fh.common.util.ConvertUtils;
import com.fh.common.web.AbstractController;
import com.fh.modules.system.entity.SysDict;
import com.fh.modules.system.model.SysDictTree;
import com.fh.modules.system.service.ISysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author Qiu,Junda
 * @date 2019年4月3日
 * @description 字典表 前端控制器
 */
@RestController
@RequestMapping("/sys/dict")
@Api("字典表")
public class SysDictController extends AbstractController{
	
	@Autowired
	private ISysDictService sysDictService;
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@AutoLog(value="查询字典表",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result<IPage<SysDict>> queryPageList(SysDict sysDict,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<IPage<SysDict>> result = new Result<IPage<SysDict>>();
		QueryWrapper<SysDict> queryWrapper = new QueryWrapper<SysDict>(sysDict);
		Page<SysDict> page = new Page<SysDict>(pageNo,pageSize);
		//排序逻辑 处理
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		if(ConvertUtils.isNotEmpty(column) && ConvertUtils.isNotEmpty(order)) {
			if(Constant.ORDER_ASC.equals(order)) {
				queryWrapper.orderByAsc(ConvertUtils.camelToUnderline(column));
			}else {
				queryWrapper.orderByDesc(ConvertUtils.camelToUnderline(column));
			}
		}
		IPage<SysDict> pageList = sysDictService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	 * @功能：获取树形字典数据
	 * @param sysDict
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/treeList", method = RequestMethod.GET)
	@ApiOperation("查询字典表树")
	@AutoLog(value="查询字典表树",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result<List<SysDictTree>> treeList(SysDict sysDict,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<List<SysDictTree>> result = new Result<>();
		LambdaQueryWrapper<SysDict> query = new LambdaQueryWrapper<>();
		String dictName = sysDict.getDictName();
		List<SysDictTree> treeList = new ArrayList<>();
		if(ConvertUtils.isNotEmpty(dictName)) {
			query.like(true, SysDict::getDictName, dictName);
			query.eq(true, SysDict::getDelFlag, "0");
			query.orderByDesc(true, SysDict::getCreateTime);
			List<SysDict> list = sysDictService.list(query);
			for (SysDict node : list) {
				treeList.add(new SysDictTree(node));
			}
		}else {
			treeList=sysDictService.queryDictByParentId("");
		}
		result.setSuccess(true);
		result.setResult(treeList);
		return result;
	}
	
	/**
	 * 获取字典数据
	 * @param dictCode
	 * @return
	 */
	@RequestMapping(value = "/getDictItems/{dictCode}", method = RequestMethod.GET)
	@AutoLog(value="获取字典数据",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result<List<Map<String, String>>> getDictItems(@PathVariable String dictCode) {
		log.info(" dictCode : "+ dictCode);
		Result<List<Map<String,String>>> result = new Result<List<Map<String,String>>>();
		List<Map<String,String>> ls = null;
		try {
			 ls = sysDictService.queryDictItemsByCode(dictCode);
			 result.setSuccess(true);
			 result.setResult(ls);
		} catch (Exception e) {
			log.info(e.getMessage());
			result.error500("操作失败");
			return result;
		}
		
		return result;
	}
	
	/**
	 * 获取字典数据
	 * @param dictCode
	 * @return
	 */
	@RequestMapping(value = "/getDictText/{dictCode}/{key}", method = RequestMethod.GET)
	@AutoLog(value="获取字典数据",logType=CommonConstant.LOG_TYPE_QUERY)
	public Result<String> getDictItems(@PathVariable("dictCode") String dictCode, @PathVariable("key") String key) {
		log.info(" dictCode : "+ dictCode);
		Result<String> result = new Result<String>();
		String text = null;
		try {
			text = sysDictService.queryDictTextByKey(dictCode, key);
			 result.setSuccess(true);
			 result.setResult(text);
		} catch (Exception e) {
			log.info(e.getMessage());
			result.error500("操作失败");
			return result;
		}
		return result;
	}
	
	/**
	 * @功能：新增
	 * @param sysDict
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ApiOperation("新增字典表")
	@AutoLog("新增字典表")
	public Result<SysDict> add(@RequestBody SysDict sysDict) {
		Result<SysDict> result = new Result<SysDict>();
		try {
			//查询dictCode的数量
			int existCount=sysDictService.count(new QueryWrapper<SysDict>().lambda().eq(SysDict::getDelFlag, 0).eq(SysDict::getDictCode, sysDict.getDictCode()));
			if(existCount>0) {
				result.error500("保存失败：字典编码重复");
			}else {
				sysDict.setDelFlag(CommonConstant.DEL_FLAG_0);
				sysDict.setCreateTime(new Date());
				if(ConvertUtils.isNotEmpty(sysDict.getParentId())) {
					SysDict parentDict=sysDictService.getById(sysDict.getParentId());
					Assert.isNull(parentDict, "新增失败：父字典不存在");
					sysDict.setParentName(parentDict.getDictName());
				}
				sysDictService.save(sysDict);
				result.success("保存成功");
			}
				
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	 * @功能：编辑
	 * @param sysDict
	 * @return
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	@ApiOperation("修改字典表")
	@AutoLog("修改字典表")
	public Result<SysDict> edit(@RequestBody SysDict sysDict) {
		Result<SysDict> result = new Result<SysDict>();
		SysDict sysdict = sysDictService.getById(sysDict.getId());
		if(sysdict==null) {
			result.error500("保存失败：未找到对应实体");
		}else {
			if(!sysdict.getDictCode().equals(sysDict.getDictCode())) {
				//查询dictCode的数量
				int existCount=sysDictService.count(new QueryWrapper<SysDict>().lambda().eq(SysDict::getDelFlag, 0).eq(SysDict::getDictCode, sysDict.getDictCode()));
				if(existCount>0) {
					result.error500("保存失败：字典编码重复");
					return result;
				}
			}
			sysDict.setUpdateTime(new Date());
			boolean ok = sysDictService.updateById(sysDict);
			if(ok) {
				result.success("保存成功");
			}
		}
		return result;
	}
	
	/**
	 * @功能：删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	@ApiOperation("单个删除字典表")
	@AutoLog("删除字典表")
	public Result delete(@RequestParam(name="id",required=true) String id) {
		sysDictService.deleteDict(id);
		return Result.ok("删除成功！");
	}
	
	/**
	 * @功能：批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	@ApiOperation("批量删除字典表")
	@AutoLog("批量删除字典表")
	public Result deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		sysDictService.deleteDictByIds(ids);
		return Result.ok("批量删除成功！");
	}
}
